package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"wechat/models/mysqlinit"

	"wechat/personrpc/internal/svc"
	"wechat/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *personrpc.UpdateRequest) (*personrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	var upda mysqlinit.Person
	mysqlinit.DB.Debug().Where("id=?", in.Id).Find(&upda)
	if upda.ID == 0 {
		return nil, fmt.Errorf("没有这条数据，无法修改")
	}
	if upda.Name == in.Name {
		return nil, fmt.Errorf("不能修改相同的名称,请重新输入")
	}
	var user mysqlinit.User

	mysqlinit.DB.Debug().Where("id=?", uint(in.UserId)).Find(&user)
	if user.ID != uint(in.UserId) {
		return nil, fmt.Errorf("请前往登录")
	}
	person := mysqlinit.Person{
		Model:   gorm.Model{ID: uint(in.Id)},
		Image:   in.Image,
		Name:    in.Name,
		UserId:  in.UserId,
		Info:    in.Info,
		Address: in.Address,
	}
	mysqlinit.DB.Debug().Updates(person)
	return &personrpc.UpdateResponse{
		Id: int64(person.ID),
	}, nil
}
